const service = require("../../../service/port.js");
const activityService = require("../../../service/activity")
const { returnMoney } = require('../../../service/other');
const rules = require("../../../utils/util.js");
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast.js";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isPaying : false,
    totalMoney: 0,
    postageMoney: 0,
    remark: "",
    checked: true,
    isOnLine: true, //是否线上
    showbtn: true,
    showaddbtn: false,
    productInfo: {}, //详情
    orderdetailList: [],
    currentAddress: {
      receiptName: '***',
      receiptMobile: '***',
      provinceName: '***',
      cityName: '***',
      areaName: '***',
      receiptAddress: '***'
    },
    currentStore: {},
    storeList: [],
    diamondNum: 0, //拥有总钻石
    deductionMoney: 0, //可兑换钱数(元)
    deductionDiamond: 0, //sku抵扣钻石数
    ownSpec: "",
    actualPay: 0, //实际付款数（元）
    cancheck: false,
    services: [],
    postList: [],
    showcoupon: false,
    type: "",
    spuDetail: "",
    spuId: "",
    currentNum: "",
    activity: "",
    promotiomIds: "",

    distributionType: 0, //配送方式
    showtype: false, //配送方式弹出窗
    showtype1: false, //配送方式弹出窗
    showtype2: false, //配送方式弹出窗
    distributionType1: 0, //配送方式
    distributionType2: 0, //配送方式
    showTime: false, //时间段
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    cards: 0, //储值卡扣除
    member: 0, //会员卡扣除
    type1: true, //即时配送或上门取货
    type2: false, //快递物流或上门取货
    type3: false, //快递物流或即时配送
    type4: false, //收货时段
    showstoreList: false, //门店列表
    timelyDelivery: 1,
    timetype: 1,//时间类型
    sendstartTime: "",//收货时段开始时间
    sendendTime: "",//收货时段结束时间
    oldMoney: '',
    newMoney: '',
    useCard: false,
    oldCard: '',
    oldMember: '',

  },
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);

    this.setData({
      checked: event.detail,
    });
    if (event.detail) {
      this.setData({
        actualPay: (this.data.productInfo.currentInfo.killMoney *
          this.data.productInfo.currentnum + this.data.postageMoney).toFixed(2),
        //deductionDiamond: this.data.deductionMoney * 50
      });
    } else {
      this.setData({
        actualPay: (this.data.productInfo.currentInfo.killMoney *
          this.data.productInfo.currentnum + this.data.postageMoney).toFixed(2),
        //deductionDiamond: 0
      });
    }
  },
  computedCardAndMember() {

    let data = {
      id: wx.getStorageSync("userInfo").id
    }

    service.getBalanceByCosId(data, (res) => {
      if (res.code == '00000') {
        console.log(1111,this.data.actualPay)
        let actualPay = String(Number(this.data.actualPay).toFixed(2))


        let cards = res.data.balance || 0
        let member = res.data.vipMoney || 0
        console.log(cards, member)

        this.setData({
          oldCard: cards,
          oldMember: member
        })

        this.computedRealMoney(actualPay, cards, member)
      }
    })
  },
  computedRealMoney(actualPay, cards, member) {
    actualPay = Number((actualPay / 100).toFixed(2))
    if (cards >= actualPay) { // 储蓄卡余额够用
      this.setData({
        actualPay: 0,
        cards: actualPay.toFixed(2),
        member: 0
      })
      return
    };
    if (cards < actualPay) { // 储蓄卡余额不够
      let diff1 = actualPay - cards
      if (member >= diff1) { // 会员卡余额够用
        this.setData({
          actualPay: 0,
          cards: cards,
          member: diff1
        })
      } else { // 会员卡余额不够
        this.setData({
          actualPay: (diff1 - member).toFixed(2),
          cards: cards,
          member: member
        })
      }
    }
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  chooseTime(e) {
    if (this.data.timetype == 1) {
      this.setData({
        sendstartTime: rules.formatTime2(new Date(e.detail)),
        showTime: false
      })
    } else {
      this.setData({
        sendendTime: rules.formatTime2(new Date(e.detail)),
        showTime: false
      })
    }

  },
  onClose() {
    this.setData({
      show: false,
      showtype: false,
      showtype1: false,
      showTime: false,
      showstoreList: false
    });
  },
  showtypePop(e) {
    //console.log(e.currentTarget.dataset)
    if (e.currentTarget.dataset.index == "1") {
      this.setData({
        showtype: true
      })
    } else if (e.currentTarget.dataset.index == "2") {
      this.setData({
        showtype1: true
      })
    } else if (e.currentTarget.dataset.index == "3") {
      this.setData({
        showtype2: true
      })
    } else if (e.currentTarget.dataset.index == "4") {
      this.setData({
        showTime: true,
        timetype: 1
      })
    } else {
      this.setData({
        showTime: true,
        timetype: 2
      })
    }

  },
  onChange1(event) {
    this.setData({
      distributionType: event.detail,
    });
  },
  onClick1(event) {
    const {
      name,
      index
    } = event.currentTarget.dataset;
    if (index == 1) {
      this.setData({
        distributionType: name,
      });
    } else if (index == 2) {
      this.setData({
        distributionType1: name,
      });
    } else {
      this.setData({
        distributionType2: name,
      });
    }

  },
  onChange2(event) {
    this.setData({
      distributionType1: event.detail,
    });
  },
  onChange3(event) {
    this.setData({
      distributionType2: event.detail,
    });
  },
  chooseDistributionType(e) {
    this.setData({
      showtype: false,
      showtype1: false,
      showtype2: false
    })
    if (e.currentTarget.dataset.type == '1') {
      if (this.data.distributionType == '1') {
        this.setData({
          type1: false,
          type2: true,
          type3: false,
          type4: true,
          isOnLine: true,
          timelyDelivery: 2
        })
        this.changeIsOnLineStatus()
      } else {
        this.setData({
          type1: false,
          type2: false,
          type3: true,
          type4: true,
          isOnLine: false,
          timelyDelivery: 3
        })
      }
    } else if (e.currentTarget.dataset.type == '2') {
      if (this.data.distributionType1 == '1') {
        this.setData({
          type1: true,
          type2: false,
          type3: false,
          type4: false,
          isOnLine: true,
          timelyDelivery: 1
        })
        this.changeIsOnLineStatus()
      } else {
        this.setData({
          type1: false,
          type2: false,
          type3: true,
          type4: true,
          isOnLine: false,
          timelyDelivery: 3
        })
      }
    } else {
      if (this.data.distributionType2 == '1') {
        this.setData({
          type1: true,
          type2: false,
          type3: false,
          type4: false,
          isOnLine: true,
          timelyDelivery: 1
        })
        this.changeIsOnLineStatus()
      } else {
        this.setData({
          type1: false,
          type2: true,
          type3: false,
          type4: true,
          isOnLine: true,
          timelyDelivery: 2
        })
        this.changeIsOnLineStatus()
      }
    }
  },
  getStore(e) {
    //console.log(e)
    this.setData({
      showstoreList: false,
      showbtn: false,
      currentStore: e.detail
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    const info = wx.getStorageSync("activitygood")

    this.setData({
      services: info.serviceList,
      spuDetail: info.spudetail,
      spuId: info.spuId,
      currentNum: info.currentnum,
      promotiomIds: info.promotiomIds
    })
    if (wx.getStorageSync("type") == "miaosha") {


      var list = [{
        "title": info.currentInfo.skuTitle, //商品名称
        "price2": info.currentInfo.killMoney, //商品价格
        "num": info.currentnum, //订单商品数量
        "ownSpec": info.currentInfo.ownSpec, //商品规格对象
        "skuId": info.currentInfo.id, //详情表中skuId
        "image": info.currentInfo.skuImage
      }];
      var orders = [{
        "title": info.currentInfo.skuTitle, //商品名称
        "price": info.currentInfo.killMoney, //商品价格
        "num": info.currentnum, //订单商品数量
        "ownSpec": info.currentInfo.ownSpec, //商品规格对象
        "skuId": info.currentInfo.id, //详情表中skuId
        "spuId": this.data.spuId,
      }];

      this.setData({
        orderdetailList: list,
        actualPay: (info.currentInfo.killMoney * info.currentnum).toFixed(2) + this.data.postageMoney,
        oldMoney: (info.currentInfo.killMoney * info.currentnum).toFixed(2) + this.data.postageMoney,
        postList: orders,
        type: wx.getStorageSync("type"),
        activity: 1
      });

    } else if (wx.getStorageSync("type") == "coupon") {
      this.setData({
        showcoupon: true
      })
    } else if (wx.getStorageSync("type") == "group") {
      var list = [{
        "title": info.currentInfo.skuTitle, //商品名称
        "price2": info.currentInfo.groupMoney, //商品价格
        "num": info.currentnum, //订单商品数量
        "ownSpec": info.currentInfo.ownSpec, //商品规格对象
        "skuId": info.currentInfo.skuId, //详情表中skuId
        "image": info.currentInfo.skuImage
      }];
      var orders = [{
        "title": info.currentInfo.skuTitle, //商品名称
        "price": info.currentInfo.groupMoney, //商品价格
        "num": info.currentnum, //订单商品数量
        "ownSpec": info.currentInfo.ownSpec, //商品规格对象
        "skuId": info.currentInfo.skuId, //详情表中skuId
        "spuId": this.data.spuId,
      }];
      console.log(111, (info.currentInfo.groupMoney * info.currentnum).toFixed(2))
      this.setData({
        orderdetailList: list,
        actualPay: (info.currentInfo.groupMoney * info.currentnum).toFixed(2) + this.data.postageMoney,
        oldMoney: (info.currentInfo.groupMoney * info.currentnum).toFixed(2) + this.data.postageMoney,
        postList: orders,
        type: wx.getStorageSync("type"),
        activity: 2
      });

    }

    if (options.accountInfo) {
      //购物车跳进
      let actualPay = 0;
      var productInfo = JSON.parse(options.accountInfo);
      //var diamondN = wx.getStorageSync("diamondNum");
      //var skudiamond = productInfo.shoppingList[0].useDiamond;
      // console.log(productInfo);
      this.setData({
        orderdetailList: productInfo.shoppingList,
      });
      var postList = [];
      productInfo.shoppingList.forEach(item => {
        actualPay += item.price2 * item.num;
        var orders = {
          "title": item.title, //商品名称
          "price": item.price2 * 100, //商品价格
          "num": item.num, //订单商品数量
          "ownSpec": item.ownSpec, //商品规格对象
          "skuId": item.skuId, //详情表中skuId
          "useCoupons": "0",
          "spuId": this.data.spuId,
        };
        postList.push(orders)

      })
      this.setData({
        actualPay: actualPay.toFixed(2),
        postList: postList
      });

    } else {

      //this.diamondevent();
    }
    this.computedCardAndMember()
  },
  diamondevent() {
    var diamondN = wx.getStorageSync("diamondNum");
    var skudiamond = 0;
    var ownSpec = "";
    this.data.productInfo.specification[0].tag.forEach((item) => {
      if (item.id == this.data.productInfo.currentsku) {
        (skudiamond = item.useDiamond), (ownSpec = item.ownSpec);
      }
    });
    if (diamondN > 0) {
      if (diamondN > skudiamond) {
        this.setData({
          deductionDiamond: skudiamond,
          deductionMoney: skudiamond / 50,
          ownSpec: ownSpec,
          actualPay: (this.data.productInfo.currentInfo.price2 *
            this.data.productInfo.currentnum -
            skudiamond / 50 + this.data.postageMoney).toFixed(2),
        });
      } else {
        this.setData({
          deductionDiamond: Math.floor(diamondN / 50) * 50,
          deductionMoney: Math.floor(diamondN / 50),
          ownSpec: ownSpec,
          actualPay: (this.data.productInfo.currentInfo.price2 *
            this.data.productInfo.currentnum -
            Math.floor(diamondN / 50) + this.data.postageMoney).toFixed(2),
        });
      }
    } else {
      this.setData({
        deductionDiamond: 0,
        deductionMoney: 0,
        ownSpec: ownSpec,
        actualPay: (this.data.productInfo.currentInfo.price2 *
          this.data.productInfo.currentnum + this.data.postageMoney).toFixed(2),
        cancheck: true
      });
    }

  },
  goToMyAddress() {
    wx.setStorageSync("isconfirmorder", true);
    wx.navigateTo({
      url: "/pages/mine/address/index",
    });
  },
  goToSelectStore() {
    this.setData({
      showstoreList: true
    })
  },
  changeIsOnLineStatus() {

    if (!this.data.isOnLine) {
      this.setData({
        currentAddress: {},
        postageMoney: 0
      });
    } else {
      this.setData({
        currentStore: {},
      });
      service.getdefaultAddress(wx.getStorageSync("userInfo").id, (res) => {
        //console.log(res);
        this.setData({
          currentAddress: res.data[0] || {},
          showaddbtn: res.data[0] ? false : true,
        });
        if (res.data[0]) {
          this.getCarriage(res.data[0].provinceId)
        }
      });
    }
  },
  blurEvent(e) {
    this.setData({
      remark: e.detail.value,
    });
  },
  paynow() {

    if(this.data.isPaying)return;
    this.setData({ isPaying : true })

    if (this.data.isOnLine) {
      if (!this.data.currentAddress.id) {
        Toast.fail("请选择地址");
        return;
      }
    } else {
      if (!this.data.currentStore.storeName) {
        Toast.fail("请选择门店");
        return;
      }
    }
    if (this.data.timelyDelivery == 2 || this.data.timelyDelivery == 3) {
      if (this.data.sendstartTime == '' || this.data.sendendTime == '') {
        Toast.fail("请选择时间段");
        return;
      }
    }
    wx.showLoading({
      title: '加载中',
    })
    service.commitOrderMul([{
      "totalPay": Number(this.data.actualPay * 100), //总金额，单位为分
      "actualPay": Number(this.data.oldMoney), //实付金额。单位:分。如:20007，表示:200元7分
      memberPay: this.data.member * 100, //会员卡支付
      stordsPay: this.data.cards * 100, //储蓄卡支付
      wechatPay: Number(this.data.oldMoney) - this.data.member * 100 - this.data.cards * 100, //微信支付
      "freightMoney": this.data.postageMoney, //运费金额
      "damondNum": 0, //抵扣钻石数量
      "promotionIds": "", //优惠标识
      "paymentType": "1", //支付类型，1、在线支付，2、货到付款
      "postFee": "0", //邮费。单位:分。如:20007，表示:200元7分
      "customerId": wx.getStorageSync("userInfo").id, //客户id
      "buyerNick": wx.getStorageSync("userInfo").wechatNick, //买家昵称
      "buyerMessage": this.data.remark, //买家留言
      "receiverState": this.data.currentAddress.provinceName || "", //收获地址（省）
      "receiverCity": this.data.currentAddress.cityName || "", //收获地址（市）
      "receiverDistrict": this.data.currentAddress.areaName || "", //收获地址（区/县
      "receiverAddress": this.data.currentAddress.receiptAddress || "", //收获地址（街道、住址等详细地址）
      "receiverMobile": this.data.currentAddress.receiptMobile, //收货人手机
      "receiverZip": "", //收货人邮编
      "receiver": this.data.currentAddress.receiptName, //收货人name
      "invoiceType": "0", //发票类型(0无发票1普通发票，2电子发票，3增值税发票)
      "sourceType": "1", //订单来源：1:微信端 
      "isOffline": "0", //是否为线下 0否 1是
      "storeId": "", //线下门店标识
      "orderdetailList": this.data.postList,
      "orderType": this.data.spuDetail.productType,
      "companyName": this.data.spuDetail.companyName,
      "url": this.data.spuDetail.url,
      "activity": this.data.activity, //1秒杀活动，2拼团活动3.打包
      "promotionIds": this.data.promotiomIds, //活动标识 秒杀活动 拼团活动的ID
      "timelyDelivery": this.data.timelyDelivery,
      "sendstartTime": this.data.sendstartTime,
      "sendendTime": this.data.sendendTime,
      "storeId": this.data.currentStore.storeId
    }],
      (res) => {

        if (res.data == null && res.code == "00000") {
          Toast.fail("您已超过购买数量上限！");
          this.setData({ isPaying : false })
          return;
        }

        //console.log(res);
        if (res.code == 500) {
          Toast.fail("下单失败！");
          this.setData({ isPaying : false })
          return;
        }
        service.payment({
          id: res.data.id,
          orderNum: res.data.orderNum, //订单编号
          actualPay: res.data.actualPay, //res.data.actualPay//实付金额。单位:分。如:20007，表示:200元7分
          title: this.data.postList[0].title,
          openid: wx.getStorageSync("userInfo").openId,
          customerId: wx.getStorageSync("userInfo").id, //客户id
        },
          (res1) => {
            console.log(res1);
            wx.hideLoading();
            if (res1.data == null && res1.code == "00000") {
              Toast.success("支付成功");
              wx.navigateTo({
                url: '/pages/paySuccess/index',
              })

            } else {
              wx.requestPayment({
                appId: res1.data.appId,
                timeStamp: res1.data.timeStamp,
                nonceStr: res1.data.nonceStr,
                package: res1.data.package,
                signType: res1.data.signType,
                paySign: res1.data.sign,

                success(result) {

                  Toast.success("支付成功");
                  wx.navigateTo({
                    url: '/pages/paySuccess/index',
                  })
                  this.setData({ isPaying : false })
                },
                fail(result) {
                  returnMoney(res.data.orderId, res => { });
                  Toast.fail("支付失败");
                  wx.redirectTo({
                    url: '/pages/mine/order/unpayList/index'
                  })
                  this.setData({ isPaying : false })
                },
              });
            }
            // if(res1.data.return_code=='SUCCESS'&&res1.data.result_code=='SUCCESS'){

            // }else{
            //   Toast.fail(res1.data.err_code_des)
            // }
          }
        );
      }

    )

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if (wx.getStorageSync('currentAddress')) {
      //地址跳进
      //console.log(wx.getStorageSync('currentAddress'));
      this.setData({
        currentAddress: wx.getStorageSync('currentAddress'),
        isOnLine: true,
        showaddbtn: false,
      });

      this.getCarriage(wx.getStorageSync('currentAddress').provinceId)
      wx.removeStorageSync("isconfirmorder");
      wx.removeStorageSync('currentAddress')
    } else if (!wx.getStorageSync('currentStore')) {
      service.getdefaultAddress(wx.getStorageSync("userInfo").id, (res) => {
        //console.log(res);
        this.setData({
          currentAddress: res.data[0] || {},
          showaddbtn: res.data[0] ? false : true,
        });
        if (res.data[0]) {
          this.getCarriage(res.data[0].provinceId)
        }

      });
    }
    if (wx.getStorageSync('currentStore')) {
      //门店跳进
      console.log(wx.getStorageSync('currentStore'));
      this.setData({
        currentStore: wx.getStorageSync('currentStore'),
        showbtn: false,
        isOnLine: false,
        postageMoney: 0
      });
      if (this.data.checked) {
        this.setData({
          actualPay: (this.data.productInfo.currentInfo.price2 *
            this.data.productInfo.currentnum -
            this.data.deductionMoney + this.data.postageMoney).toFixed(2),

        });
      } else {
        this.setData({
          actualPay: (this.data.productInfo.currentInfo.price2 *
            this.data.productInfo.currentnum + this.data.postageMoney).toFixed(2),

        });
      }
      wx.removeStorageSync('currentStore')
      return
    }
  },
  getCarriage(provinceId) {
    activityService.getOrderFreight([{
      "spuId": this.data.spuId,
      "spuNum": this.data.currentNum,
      "freightMoney": parseFloat(this.data.actualPay),
      "areaId": provinceId
    }], res => {
      // debugger;
      this.setData({
        postageMoney: res.data ? res.data : 0,
        actualPay: parseFloat(this.data.postList[0].price) * this.data.currentNum + parseFloat(res.data)
      })
      this.computedCardAndMember()
    })

    // if (this.data.orderdetailList[0].num >= this.data.spuDetail.freeNum || this.data.actualPay >= this.data.spuDetail.freeMoney) {
    //   this.setData({
    //     postageMoney: 0,
    //   })
    // } else {
    //   var str = JSON.stringify(this.data.orderdetailList)
    //   let products = JSON.parse(str);
    //   let carrigeList = [];
    //   var self = this;

    //   function getpostTage() {
    //     if (products.length > 0) {
    //       let proitem = products.pop();
    //       //console.log(proitem);
    //       service.getCarriage({
    //         "skuId": proitem.skuId,
    //         "provinceId": provinceId
    //       }, res => {
    //         //console.log(res)
    //         if (res.data.length != 0) {
    //           carrigeList.push(res.data[0].postageMoney);

    //         }
    //         getpostTage()
    //       })
    //     } else {
    //     //console.log(carrigeList)
    //     if (carrigeList.length == 0) {
    //       self.setData({
    //         postageMoney: 0,
    //       })
    //     } else {
    //       let max = Math.max(...carrigeList)
    //       self.setData({
    //         postageMoney: max,
    //       })
    //     }
    //     let actualPay = 0;
    //     self.data.orderdetailList.forEach(item => {
    //       actualPay += item.price2 * item.num;
    //     })
    //     var total = parseFloat(actualPay) + self.data.postageMoney
    //     self.setData({
    //       actualPay: total.toFixed(2)

    //     });
    //   }

    // }
    // getpostTage()

    //}


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
});